package com.atguigu.day03;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class Example3 {
    public static void main(String[] args)throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<com.atguigu.day02.Example2.Event> streamSource = env.addSource(new com.atguigu.day02.Example2.MySource());
        KeyedStream<com.atguigu.day02.Example2.Event, String> keyedStream = streamSource.keyBy(x -> x.name);
        WindowedStream<com.atguigu.day02.Example2.Event, String, TimeWindow> windowedStream = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        windowedStream.aggregate(new Example2.CountACC(), new ProcessWindowFunction<Long, Example1.UserViewCountPerWindow, String, TimeWindow>() {
            @Override
            public void process(String key, Context context, Iterable<Long> elements, Collector<Example1.UserViewCountPerWindow> out) throws Exception {
                out.collect(new Example1.UserViewCountPerWindow(
                        key,
                        elements.iterator().next(),
                        context.window().getStart(),
                        context.window().getEnd()
                ));
            }
        }).print();
        env.execute();
    }
}
